<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="车牌号">
              <a-input placeholder="请输入车牌号" v-model="queryParam.plateNumber"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>
      <a-button type="primary" icon="download" @click="handleExportXls('车辆预约进出厂信息表')">导出</a-button>
      <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">
        <a-button type="primary" icon="import">导入</a-button>
      </a-upload>
      <!-- 高级查询区域 -->
      <j-super-query :fieldList="superFieldList" ref="superQueryModal" @handleSuperQuery="handleSuperQuery"></j-super-query>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel"><a-icon type="delete"/>删除</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
        <span style="float:right;">
          <a-popover title="自定义列" trigger="click" placement="leftBottom">
                  <template slot="content">
                    <div style="width: 400px">
                      <draggable
                        v-model="settingColumns"
                        v-bind="dragOptions"
                        @start="dragging = true"
                        @end="handleDragEnd"
                        handle=".drag-handle"
                      >
                        <transition-group type="transition" :name="!dragging ? 'flip-list' : null">
                          <div v-for="(col, index) in settingColumns" :key="col" style="margin-bottom: 8px; cursor: move;">
                            <a-row>
                              <a-col :span="2">
                                <a-icon type="menu" class="drag-handle" style="margin-right: 8px;"/>
                              </a-col>
                              <a-col :span="20">
                                <a-checkbox :value="col" checked disabled>
                                  <j-ellipsis :value="getColumnTitle(col)" :length="20"></j-ellipsis>
                                </a-checkbox>
                              </a-col>
                              <a-col :span="2">
                                <a-icon type="close" @click="removeColumn(index)"/>
                              </a-col>
                            </a-row>
                          </div>
                        </transition-group>
                      </draggable>
                      <a-divider />
                      <div style="max-height: 200px; overflow-y: auto;">
                        <a-row>
                          <template v-for="item in defColumns">
                            <template v-if="item.key!=='rowIndex' && item.dataIndex!=='action' && !settingColumns.includes(item.dataIndex)">
                              <a-col :span="12" style="margin-bottom: 8px;">
                                <a-checkbox :value="item.dataIndex" @change="(e) => toggleColumn(item.dataIndex, e.target.checked)">
                                  <j-ellipsis :value="item.title" :length="10"></j-ellipsis>
                                </a-checkbox>
                              </a-col>
                            </template>
                          </template>
                        </a-row>
                      </div>
                    </div>
                  </template>
              <a><a-icon type="setting" />设置</a>
            </a-popover>

        </span>
      </div>

      <a-table
        :key="tableKey"
        ref="table"
        size="middle"
        :scroll="{x:true}"
        bordered
        rowKey="id"
        :columns="tableColumns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        class="j-table-force-nowrap"
        @change="handleTableChange">

        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text,record">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img v-else :src="getImgView(text)" :preview="record.id" height="25px" alt="" style="max-width:80px;font-size: 12px;font-style: italic;"/>
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button
            v-else
            :ghost="true"
            type="primary"
            icon="download"
            size="small"
            @click="downloadFile(text)">
            下载
          </a-button>
        </template>

        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>

          <a-divider type="vertical" />
          <a-dropdown>
            <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a @click="handleDetail(record)">详情</a>
              </a-menu-item>
              <a-menu-item>
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>

      </a-table>
    </div>

    <buss-car-reservation-info-modal ref="modalForm" @ok="modalFormOk"></buss-car-reservation-info-modal>
  </a-card>
</template>

<script>

  import '@/assets/less/TableExpand.less'
  import { mixinDevice } from '@/utils/mixin'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import BussCarReservationInfoModal from './modules/BussCarReservationInfoModal'
  import {filterMultiDictText} from '@/components/dict/JDictSelectUtil'
  import draggable from 'vuedraggable'

  export default {
    name: 'BussCarReservationInfoList',
    mixins:[JeecgListMixin, mixinDevice],
    components: {
      BussCarReservationInfoModal,
      draggable
    },
    data () {
      return {
        isOpenSettingColumns:true,
        tableKey: Date.now(), // 初始值
        dragOptions: {
          animation: 150,
          ghostClass: 'ghost'
        },
        dragging: false,

        description: '车辆预约进出厂信息表管理页面',
        // 表头
        columns: [
          // {
          //   title: '#',
          //   dataIndex: '',
          //   key:'rowIndex',
          //   width:60,
          //   align:"center",
          //   customRender:function (t,r,index) {
          //     return parseInt(index)+1;
          //   }
          // },
          // {
          //   title:'数据来源类型',
          //   align:"center",
          //   dataIndex: 'sourceType'
          // },
          // {
          //   title:'数据来源id',
          //   align:"center",
          //   dataIndex: 'source'
          // },
          // {
          //   title:'车牌省',
          //   align:"center",
          //   dataIndex: 'province'
          // },
          // {
          //   title:'车牌体',
          //   align:"center",
          //   dataIndex: 'plateBody'
          // },
          {
            title:'车牌号',
            align:"center",
            dataIndex: 'plateNumber',
            key: 'plateNumber'
          },
          {
            title:'司机姓名',
            align:"center",
            dataIndex: 'driverName',
            key: 'driverName'
          },
          {
            title:'联系电话',
            align:"center",
            dataIndex: 'driverPhone',
            key: 'driverPhone'
          },
          {
            title:'进厂目的',
            align:"center",
            dataIndex: 'purpose_dictText',
            key: 'purpose_dictText'
          },
          {
            title:'预约进厂时间',
            align:"center",
            dataIndex: 'reservationTime',
            key: 'reservationTime'
          },
          {
            title:'进厂时间',
            align:"center",
            dataIndex: 'inTime',
            key: 'inTime'
          },
          {
            title:'进厂放行人',
            align:"center",
            dataIndex: 'inPermissionPerson',
            key: 'inPermissionPerson'
          },
          {
            title:'出厂时间',
            align:"center",
            dataIndex: 'outTime',
            key: 'outTime'
          },
          {
            title:'出厂放行人',
            align:"center",
            dataIndex: 'outPermissionPerson',
            key: 'outPermissionPerson'
          },
          {
            title:'备注',
            align:"center",
            dataIndex: 'remark',
            key: 'remark'
          },
          {
            title:'预约人',
            align:"center",
            dataIndex: 'createBy_dictText',
            key: 'createBy_dictText'
          },
          {
            title:'预约部门',
            align:"center",
            dataIndex: 'sysOrgCode_dictText',
            key: 'sysOrgCode_dictText'
          },
          {
            title:'预约时间',
            align:"center",
            dataIndex: 'createTime',
            key: 'createTime'
          }
          // ,
          // {
          //   title: '操作',
          //   dataIndex: 'action',
          //   key: 'action',
          //   align:"center",
          //   fixed:"right",
          //   width:147,
          //   scopedSlots: { customRender: 'action' }
          // }
        ],
        settingColumns: [],
        defColumns: [
          {
            title: '#',
            dataIndex: '',
            key: 'rowIndex',
            width: 60,
            align: "center",
            customRender: (t, r, index) => parseInt(index) + 1
          },
          {
            title:'车牌号',
            align:"center",
            dataIndex: 'plateNumber',
            key: 'plateNumber'
          },
          {
            title:'司机姓名',
            align:"center",
            dataIndex: 'driverName',
            key: 'driverName'
          },
          {
            title:'联系电话',
            align:"center",
            dataIndex: 'driverPhone',
            key: 'driverPhone'
          },
          {
            title:'进厂目的',
            align:"center",
            dataIndex: 'purpose_dictText',
            key: 'purpose_dictText'
          },
          {
            title:'预约进厂时间',
            align:"center",
            dataIndex: 'reservationTime',
            key: 'reservationTime'
          },
          {
            title:'进厂时间',
            align:"center",
            dataIndex: 'inTime',
            key: 'inTime'
          },
          {
            title:'进厂放行人',
            align:"center",
            dataIndex: 'inPermissionPerson',
            key: 'inPermissionPerson'
          },
          {
            title:'出厂时间',
            align:"center",
            dataIndex: 'outTime',
            key: 'outTime'
          },
          {
            title:'出厂放行人',
            align:"center",
            dataIndex: 'outPermissionPerson',
            key: 'outPermissionPerson'
          },
          {
            title:'备注',
            align:"center",
            dataIndex: 'remark',
            key: 'remark'
          },
          {
            title:'预约人',
            align:"center",
            dataIndex: 'createBy_dictText',
            key: 'createBy_dictText'
          },
          {
            title:'预约部门',
            align:"center",
            dataIndex: 'sysOrgCode_dictText',
            key: 'sysOrgCode_dictText'
          },
          {
            title:'预约时间',
            align:"center",
            dataIndex: 'createTime',
            key: 'createTime'
          }
        ],


        url: {
          list: "/bussCarReservationInfo/bussCarReservationInfo/list",
          delete: "/bussCarReservationInfo/bussCarReservationInfo/delete",
          deleteBatch: "/bussCarReservationInfo/bussCarReservationInfo/deleteBatch",
          exportXlsUrl: "/bussCarReservationInfo/bussCarReservationInfo/exportXls",
          importExcelUrl: "bussCarReservationInfo/bussCarReservationInfo/importExcel",

        },
        dictOptions:{},
        superFieldList:[],
      }
    },

    watch: {
      settingColumns: {
        deep: true,
        // immediate: true,
        handler() {
          this.$nextTick(() => {
            this.tableKey = Date.now(); // 触发表格重新渲染
          });
        }
      }
    },


    created() {

      this.getSuperFieldList();
      this.loadColumnSettings();

      // 初始化显示列（排除序号列和操作列）
      if (this.settingColumns.length === 0) {
        this.settingColumns = this.defColumns
          .filter(col => col.dataIndex && col.dataIndex !== 'action' && col.key !== 'rowIndex')
          .map(col => col.dataIndex || col.key);
      }

    },
    computed: {

      tableColumns() {
        // 序号列
        const indexColumn = {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: "center",
          customRender: (t, r, index) => parseInt(index) + 1
        };

        // 动态列
        const mainColumns = this.settingColumns
          .map(key => this.defColumns.find(col => col.dataIndex === key || col.key === key))
          .filter(Boolean)
          .map(col => ({...col})); // 创建新对象

        // 操作列
        const actionColumn = {
          title: '操作',
          dataIndex: 'action',
          key: 'action',
          align: "center",
          fixed: "right",
          width: 147,
          scopedSlots: { customRender: 'action' }
        };

        return [indexColumn, ...mainColumns, actionColumn];
      },



      importExcelUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      },
    },
    methods: {

      handleDragEnd() {
        this.dragging = false;
        this.saveColumnSettings();
        this.tableKey = Date.now(); // 强制刷新表格
      },

      toggleColumn(col, checked) {
        if (checked) {
          this.settingColumns.push(col);
        } else {
          this.settingColumns = this.settingColumns.filter(c => c !== col);
        }
        this.saveColumnSettings();
        this.tableKey = Date.now(); // 强制刷新
      },

      removeColumn(index) {
        this.settingColumns.splice(index, 1);
        this.saveColumnSettings();
        this.tableKey = Date.now(); // 强制刷新
      },


      loadColumnSettings() {
        try {
          const savedSettings = localStorage.getItem('carReservationColumns');
          if (savedSettings) {
            // 验证并过滤无效的列设置
            const validColumns = this.defColumns
              .filter(col => col.dataIndex && col.dataIndex !== 'action' && col.key !== 'rowIndex')
              .map(col => col.dataIndex);

            this.settingColumns = JSON.parse(savedSettings)
              .filter(col => validColumns.includes(col));
          }

          // 设置默认值
          if (!this.settingColumns || this.settingColumns.length === 0) {
            this.settingColumns = this.defColumns
              .filter(col => col.dataIndex && col.dataIndex !== 'action' && col.key !== 'rowIndex')
              .map(col => col.dataIndex);
          }
        } catch (e) {
          console.error('加载列设置失败:', e);
          this.settingColumns = this.defColumns
            .filter(col => col.dataIndex && col.dataIndex !== 'action' && col.key !== 'rowIndex')
            .map(col => col.dataIndex);
        }
      },

      saveColumnSettings() {
        // 保存到localStorage
        localStorage.setItem('carReservationColumns', JSON.stringify(this.settingColumns));
      },



      onColSettingsChange(checkedValues) {
        this.settingColumns = checkedValues;
        this.saveColumnSettings();
      },


      getColumnTitle(key) {
        const col = this.defColumns.find(c =>
          c.dataIndex === key || c.key === key || c.title === key
        );
        return col ? col.title : key;
      },


      initDictConfig(){
      },
      getSuperFieldList(){
        let fieldList=[];
        // fieldList.push({type:'int',value:'sourceType',text:'数据来源类型',dictCode:''})
        // fieldList.push({type:'string',value:'source',text:'数据来源id',dictCode:''})
        // fieldList.push({type:'string',value:'province',text:'车牌省',dictCode:''})
        // fieldList.push({type:'string',value:'plateBody',text:'车牌体',dictCode:''})
        fieldList.push({type:'string',value:'plateNumber',text:'车牌号',dictCode:''})
        fieldList.push({type:'string',value:'driverName',text:'司机姓名',dictCode:''})
        fieldList.push({type:'string',value:'driverPhone',text:'联系电话',dictCode:''})
        fieldList.push({type:'string',value:'purpose',text:'进厂目的',dictCode:'driver_purpose'})
        fieldList.push({type:'datetime',value:'reservationTime',text:'预约进厂时间'})
        fieldList.push({type:'datetime',value:'inTime',text:'进厂时间'})
        fieldList.push({type:'string',value:'inPermissionPerson',text:'进厂放行人',dictCode:''})
        fieldList.push({type:'datetime',value:'outTime',text:'出厂时间'})
        fieldList.push({type:'string',value:'outPermissionPerson',text:'出厂放行人',dictCode:''})
        fieldList.push({type:'string',value:'remark',text:'备注',dictCode:''})
        fieldList.push({type:'string',value:'createBy',text:'预约人',dictCode:''})
        fieldList.push({type:'string',value:'sysOrgCode',text:'预约部门',dictCode:''})
        fieldList.push({type:'datetime',value:'createTime',text:'预约时间'})
        this.superFieldList = fieldList
      }
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';

  .flip-list-move {
    transition: transform 0.5s;
  }
  .no-move {
    transition: transform 0s;
  }
  .ghost {
    opacity: 0.5;
    background: #c8ebfb;
  }
  .drag-handle {
    cursor: move;
    cursor: -webkit-grabbing;
  }
</style>